package bookManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-11-30
 * Time:15:51
 */
public class UesrDAO {
    public User findUserByname(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //建立连接
            connection = DBUtil.getConnection();
            //构建sql语句
            String sql = "select * from user where name = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            //执行SQL语句
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                //此处不应该new User 应该根绝 isadmin 值\
                //来决定new 一个 admin 或 normaluser
                boolean isadmin = (resultSet.getInt("isAdmin") == 1);
                //换句话说要new的是admin 和normaluser 所以可以把USER设置为抽象类
                //final 修饰变量 变量不能被更改
                //final 修饰方法 方法不能被重写
                //final 修饰类  类不能被继承
                User user = null;
                if (isadmin){
                    user = new Admin();
                }else {
                    user = new NormalUser();
                }
                user.setUserId(resultSet.getInt("userId"));
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
                //构造好user之后直接返回
                return user;
            }
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }

    public static void main(String[] args) {
        UesrDAO uesrDAO = new UesrDAO();
       User user = uesrDAO.findUserByname("admin");
        System.out.println(user);
    }
}
